<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>日程管理</title>
	<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0, maximum-scale=1.0">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="format-detection" content="telephone=no">
    <link type="text/css" rel="stylesheet" media="screen" href="__PUBLIC__/app/css/mrs.css{$JSDEBUG}"/>
    <link type="text/css" rel="stylesheet" media="screen" href="__PUBLIC__/app/css/media.css{$JSDEBUG}"/>
    <script type="text/javascript" src="__PUBLIC__/app/js/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">
	    $(function() {
	        tab(".manage li", ".time_box", 1);
	    })
	    
	    function tab(a, b, c) {
	        if (c == 1) {
	            $(a).click(function() {
	                var index = $(this).index();
	                $(this).addClass("on").siblings().removeClass("on");
	                $(b).hide();
	                $(b).eq(index).show();
	            })
	        } else {
	            $(a).hover(function() {
	                var index = $(this).index();
	                $(this).addClass("on").siblings().removeClass("on");
	                $(b).hide();
	                $(b).eq(index).show();
	            })
	        }
	    }
	    
    </script>
    <style>
    
    	.time_box li.hasOrder a ,
    	.time_box li.yuliu a ,
    	.time_box li.multiTime a {
		    padding: 7px 0;
		    height: 50px;
		    line-height: 25px;
		}
		
    	.guoqi {background: #eaeaea !important;color: #bbb !important;}
    	.guoqi a{background: #eaeaea !important;color: #bbb !important;}
    	.yuliu,.hasOrder,.multiTime{background: #666 !important;color: #fff !important;}
    	.yuliu a,.hasOrder a,.multiTime a{background: #666 !important;color: #fff !important;}
    </style>
</head>
<body style="background:#f7f7f9;">
	<include file="Public/customHeaderNoBack" title="日程管理" url="{:U('Beautician/scheduleManage')}"/>
	<section class="mrs_sec">
      <div class="tab">
          <ul class="manage">
              <li class="on"><a href="javascript:;">今天<span>{$today|date='n月j日',###}</span></a></li>
              <li><a href="javascript:;">明天<span></span></a></li>
              <li><a href="javascript:;">后天<span></span></a></li>
          </ul>
          <div class="time_box clear" id="today" data-time="{$today}">
            <ul>
            </ul>
          </div>
          <div class="time_box clear" style="display:none" id="tomorrow" data-time="{$today}">
            <ul>
            </ul> 
          </div>
          <div class="time_box clear"  style="display:none" id="afterTomorrow" data-time="{$today}">
            <ul>
            </ul>
          </div>
          <div class="edit_kuang">
            <div class="edit">
             <ul class="clear">
               <li><input type="button" value="休息" class="rest"></li>
               <li><input type="button" value="上班" class="work" id="submitSetting"></li>
             </ul>
            </div>
          </div>
          <div class="all_tips">
             <dd><span><i></i>不可编辑</span><span><i></i>上班</span><span><i></i>休息</span><span><i></i>编辑</span></dd>
             <p>注：每次只能设置三天内可预约时间，三天后需要重新设置，如未设置则无法被线上预约。</p>
          </div>
       </div>
	</section>
	<include file="Public/beautician-footer" />
	<script>
var orderTimes, service_time_config_start, service_time_config_end;
	
	function createTimeDom(wrap, data, start, end) {
		var html = '',
			dateObj = new Date();
			currentTime = Math.floor(dateObj.getTime()/1000),
			startTime = 0;
			
		var html = '';
		var time = Math.floor(new Date().getTime()/1000);	
		for (var n = data.day_start; n < data.day_end;) {
			n  += 3600;
			var hour = (new Date(n * 1000)).getHours() + ':00';
			if (n < start || n > end) {
				html += '<li data-time="'+n+'"><a>'+hour+'</a></li>';
			} else if (n >= start && n <= end){
				if (n > time) {
					html += '<li class="gogoing" data-time="'+n+'"><a><span>'+hour+'</span><label>休息</label></a></li>';
				} else {
					html += '<li class="guoqi" data-time="'+n+'"><a>'+hour+'</a></li>';
				}
			}
		}
		
		wrap.attr('data-time', data.day_start);
		var $timeSelectObj = $(html);
		wrap.find('ul').append($timeSelectObj);
		
		var orderTimeArr = [];
		if (orderTimes) {
			$.map(orderTimes, function (value, index) {
				orderTimeArr.push(parseInt(index));
			});
		}
		
		if (data.setting != '0') {
			if (!$.isEmptyObject(data.setting)) {
				var settings = data.setting;
				
				for (var i in settings) {
					if (settings.hasOwnProperty(i)) {
						var settingEnd = parseInt(settings [i].end);
						
						for (var m = parseInt(settings [i].start); m < settingEnd; ) {
							if (m > time) {
								var orderElme = $(wrap).find("[data-time='"+m+"']");
								orderElme.find('a').addClass('of').find('label').html('上班');
							}
							m += 3600;
						}
					}
				}
			}
		} else {
			$timeSelectObj.each(function (i, o) {
				if ($(o).hasClass('gogoing')) {
					$(o).find('a').addClass('of').find('label').html('上班');
				}
			});
		}
		
		
		for (var j = parseInt(data.start); j < end; ) {
			var orderElme = $(wrap).find("[data-time='"+j+"']");
			if  ($.inArray(j, orderTimeArr) !== -1) {
				var serviceEnd = parseInt(orderTimes [j]);
				if (j > time) {
					orderElme.removeClass('gogoing').addClass('hasOrder').find('a label').html('已预约');
				}
				if (serviceEnd - j > 3600) {
					var hideList = Math.ceil((serviceEnd - j)/3600);
					
					j += hideList * 3600;
					if (hideList - 2 <= 0) {
						if (parseInt(orderElme.next().attr('data-time')) > time) {
							orderElme.next().removeClass('gogoing').addClass('hasOrder').addClass('multiTime').find('a label').html('已预约');
						}
						if (parseInt(orderElme.next().next().attr('data-time')) > time) {
							orderElme.next().next().removeClass('gogoing').addClass('yuliu').addClass('multiTime').find('a label').html('订单预留');
						}
					} else {
						for (var n = 0; n < hideList; n++) {
							if (parseInt(orderElme.nextAll().eq(n).attr('data-time')) > time) {
								orderElme.nextAll().eq(n).removeClass('gogoing').addClass('hasOrder').addClass('multiTime').find('a label').html('已预约');
							}
						}
						if (parseInt(orderElme.nextAll().eq(hideList).attr('data-time')) > time) {
							orderElme.nextAll().eq(hideList).removeClass('gogoing').addClass('yuliu').addClass('multiTime').find('a label').html('订单预留');
						}
					}
				} else {
					if (parseInt(orderElme.next().attr('data-time')) > time) {
						orderElme.next().removeClass('gogoing').addClass('yuliu').addClass('multiTime').find('a label').html('订单预留');
					}
					j += 3600;
				}
			}
			j += 3600;
		}
		
		$timeSelectObj.each(function(i, o){
			if ($(o).hasClass('gogoing')) {
				$(o).click(function () {
					var clickDom = $(this).find('a');
					if (clickDom.hasClass('on')) {
						clickDom.removeClass('on')
					} else {
						clickDom.addClass('on');
					}
				})
			}
		});
	}

	var pad = function(tbl) {
	    return function(num, n){
	        return (0 >= (n - ''+num.length)) ? num : (tbl[n] || (tbl[n] = Array(n + 1).join(0)))+num;
	}    
	}([]);
	
	function buildTimeSelect(data) {
		var Today = data.today;
		var Tomorrow = data.tomorrow;
		var afterTomorrow = data.afterTomorrow;
		
		$timestamp = 24 * 3600;
		createTimeDom($('#today'), Today, service_time_config_start, service_time_config_end);
		createTimeDom($('#tomorrow'), Tomorrow, service_time_config_start + $timestamp,  service_time_config_end + $timestamp);
		createTimeDom($('#afterTomorrow'), afterTomorrow, service_time_config_start + 2 * $timestamp, service_time_config_end + 2 * $timestamp);
		
		var tomorrowDate = new Date((service_time_config_start + $timestamp) * 1000);
		var afterTomorrowDate = new Date((service_time_config_start + 2 * $timestamp) * 1000);
		var tomorrowMonth = tomorrowDate.getMonth();
		var afterTomorrowMonth = afterTomorrowDate.getMonth();
		
		$('.manage li').eq(1).find('span').empty().append(++tomorrowMonth+'月'+tomorrowDate.getDate()+'日');
		$('.manage li').eq(2).find('span').empty().append(++afterTomorrowMonth+'月'+afterTomorrowDate.getDate()+'日');
	}
	
	$(function () {
		var submitSchedule;
		$.ajax({
			url: '{:U("/Beautician/getTime")}',
			dataType: '',
			success: function (result) {
				time = result.data.time;
				
				orderTimes = result.orderTimes;
				service_time_config_start = time.config_start;
				service_time_config_end = time.config_end;
				
				buildTimeSelect(time);
			}
		});
		
		function submitSetting () {
			if (submitSchedule && submitSchedule.state() == 'pending') {
				alert('数据正在提交，请等待');
				return false;
			}
			var selectData = {};
			
			$('.time_box').each(function (i, o) {
				var choseTime = {}, select = {start: 0, end: 0}, j = 0;
				var childrenLength = $(o).find('.gogoing').length;
				
				if ($(o).find('.gogoing .of').length) {
					$(o).find('.gogoing').each(function (m, go) {
						if (!$(go).find('a').hasClass('of')) {
							if (select.start != 0) {
								select.end = parseInt($(go).attr('data-time'));
								choseTime [j] = $.extend({}, select);
								select = {start: 0, end: 0};
								++j;
								
							}
						} else if ($(go).find('a').hasClass('of')){
							if (select.start == 0) {
								select.start = parseInt($(go).attr('data-time'));
							}
						}
						
						if (m == childrenLength - 1) {
							if (select.start != 0) {
								select.end = parseInt($(go).attr('data-time')) + 3600;
								choseTime [j] = $.extend({}, select);
								select = {start: 0, end: 0};
								++j;
							}
							selectData [$(o).attr('data-time')] = choseTime;
						}
					});
				} else {
					selectData [$(o).attr('data-time')] = 0;
				}
			});
			
			submitSchedule = $.ajax({
				url: '{:U("Beautician/scheduleManage")}',
				data: {setting: selectData},
				dataType: 'json',
				type: 'post',
				success: function (result) {
					if (result.status != '1') {
						alert('设置失败');
					}
				},
				error: function () {
					
				}
			});
		}
		
		$('.rest').click(function () {
			$('.time_box .on').each(function (i, o) {
				$(o).removeClass('of').find('label').html('休息');
				if (i == $('.time_box .on').length-1) {
					
					$('.time_box .on').removeClass('on');
					submitSetting();
				}
			})
		});
		
		$("#submitSetting").click(function () {
			$('.time_box .on').each(function (i, o) {
				$(o).addClass('of').find('label').html('上班');
				if (i == $('.time_box .on').length-1) {
					$('.time_box .on').removeClass('on');
					submitSetting();
				}
			})
		});
	})
	</script>
</body>
</html>